import { squardDirection } from "@/squard/work/constant"
import { colorful, compare, isInArray } from "@/utils"
import { uniqueColor } from "../local/resource"
import { Colorful, colorHex, getColor } from "../local/store"

/* 市场行为便捷指令 */
export default{
    /* 终端行为 可以下若干个传送任务 */
    terminal:{
        send(roomName:string,disRoom:string,rType:ResourceConstant,num:number):string{
            var thisRoom = Game.rooms[roomName]
            if (!thisRoom) return `[terminal] 不存在房间${roomName}`
            var thisTask = thisRoom.Public_Send(disRoom,rType,num)
            /* 查看该房间当前有几个资源传送任务 */
            var MissonNum = thisRoom.MissonNum('Structure','资源传送')
            thisTask.maxTime = MissonNum + 1
            /* 查看资源是否足够 */
            var terminal_ = Game.getObjectById(thisRoom.memory.StructureIdData.terminalID) as StructureTerminal
            var storage_ = Game.getObjectById(thisRoom.memory.StructureIdData.storageID) as StructureStorage
            if (!terminal_ || !storage_) 
            {delete thisRoom.memory.StructureIdData.terminalID;delete thisRoom.memory.StructureIdData.storageID;return colorful( `[terminal] 房间${roomName}不存在终端/仓房或记忆未更新！`,'red',true)}
            /* 查询其他资源传送任务中是否有一样的资源 */
            var Num = 0
            if (!thisRoom.memory.Misson['Structure']) thisRoom.memory.Misson['Structure'] = []
            for (var tM of thisRoom.memory.Misson['Structure'])
            {
                if (tM.name == '资源传送' && tM.data.rType == rType)    Num += tM.data.num
            }
            /* 计算资源是否满足 */
            if (terminal_.store.getUsedCapacity(rType) + storage_.store.getUsedCapacity(rType) - Num < num)
            return colorful(`[terminal] 房间${roomName} 资源${rType} 数量总合少于 ${num}，传送任务挂载失败！`,'yellow',true)
            /* 计算路费 */
            var cost = Game.market.calcTransactionCost(num,roomName,disRoom)
            if (terminal_.store.getUsedCapacity('energy') + storage_.store.getUsedCapacity('energy') < cost || cost > 150000)
            return colorful(`[terminal] 房间${roomName}-->${disRoom}资源${rType}所需路费少于 ${cost}或大于150000，传送任务挂载失败！`,'yellow',true)
            if(thisRoom.AddMisson(thisTask))
                return colorful(`[terminal] 房间${roomName}-->${disRoom}资源${rType}传送挂载成功！数量：${num}；路费：${cost}`,'green',true)
            return colorful(`[terminal] 房间${roomName}-->${disRoom}资源${rType}传送 不明原因挂载失败！`,'red',true)
        },
        Csend(roomName:string,disRoom:string,rType:ResourceConstant):string{
            var thisRoom = Game.rooms[roomName]
            if (!thisRoom) return `[terminal] 不存在房间${roomName}`
            for (var tM of thisRoom.memory.Misson['Structure'])
            {
                if (tM.name == '资源传送' && tM.data.rType == rType && tM.data.disRoom == disRoom)
                {
                    if (thisRoom.DeleteMisson(tM.id))return colorful(`[terminal] 房间${roomName}-->${disRoom}资源${rType}传送任务删除成功!`,'blue',true)
                }
            }
            return colorful(`[terminal] 房间${roomName}-->${disRoom}资源${rType}传送 不明原因删除失败！`,'red',true)
        },
        /* 查看目前房间/全局的资源传送任务 */
        show(roomName?:string):string{
            var roomList:string[] = []
            if (roomName) roomList = [roomName]
            else
            {
                if (!Memory.ControlPlan) Memory.ControlPlan = {}
                for (var rN in Memory.ControlPlan)
                {
                    roomList.push(rN)
                }
            }
            if (roomList.length <= 0) return `[terminal] 未发现房间！`
            for (var rN of roomList)
            {
                if (!Game.rooms[rN]) return `[terminal] 不存在房间${rN}！`
            }
            var str = ''
            for (var rN of roomList)
            {
                if (!Game.rooms[rN].memory.Misson['Structure']) Game.rooms[rN].memory.Misson['Structure'] = []
                if (Game.rooms[rN].MissonNum('Structure','资源传送') <= 0) continue
                str += '房间 ' + colorful(`${rN}`,'yellow',true) + '：\n'
                for (var m of Game.rooms[rN].memory.Misson['Structure'])
                {
                    if (m.name == '资源传送')
                    {
                        str += '    '+`-->${m.data.disRoom} | 资源：${m.data.rType} | 数量：` + m.data.num + ' \n'
                    }
                }
            }
            if (str == '') return `[terminal] 未发现资源传送任务！`
            return str
        },
        help():string{
            var str = '[terminal] termianl API 具体使用语法、规则如下：\n'
            
            str += Colorful('[资源传送] send(roomName:string,disRoom:string,rType:ResourceConstant,num:number):string\n',colorHex(getColor(10)))
            str += Colorful('[取消传送] Csend(roomName:string,disRoom:string,rType:ResourceConstant):string\n',colorHex(getColor(20)))
            str += Colorful('[查看所有传送任务] show(roomName?:string):string\n',colorHex(getColor(30)))
            return str
        }
    },
    /* 市场行为 */
    market:{
        // 交易订单
        deal(roomName:string,id:string,amount:number):number{
            return Game.market.deal(id, amount, roomName);
        },
        // 查询订单
        look(rType:ResourceConstant,marType:"buy"|"sell"):string
        {
            var HistoryList = Game.market.getHistory(rType)
            var allNum:number = 0
            for (var ii of HistoryList)
            {
                allNum += ii.avgPrice
            }
            var avePrice = allNum / HistoryList.length
            var list = Game.market.getAllOrders({type: marType, resourceType: rType});
            /* 按照价格从上到下 */
            var newList = list.sort(compare('price'))
            var result = `当前市场上资源${rType}的${marType}订单如下:\n`
            if (rType == 'pixel' as ResourceConstant)
            {
                for (var i of list)
                {
                    result += `\tID:${i.id} 数量:${i.amount} 价格:${i.price} 坐标:${i.roomName} \n`
                }
                return result
            }
            for (var i of newList)
            {
                var priceColor:Colors = 'green'
                var roomColor:Colors = 'green'
                if (i.price > avePrice && i.price - avePrice > 10) priceColor = 'red'
                if (i.price > avePrice && i.price - avePrice <= 10) priceColor = 'yellow'
                if (i.price <= avePrice) priceColor = 'green'
                LoopB:
                for (var roomName in Memory.ControlPlan)
                {
                    var cost = Game.market.calcTransactionCost(1000,roomName as string,i.roomName)
                    if (cost >= 7000) {roomColor = 'red';break LoopB}
                    else if (cost < 700 && cost >= 500) {roomColor = 'yellow';break LoopB}
                    roomColor = 'green'
                }
                result += `\tID:${i.id} ` + `数量:${i.amount} 价格:`+ colorful(`${i.price}`,priceColor?priceColor:'blue',true) +` 坐标: ` + colorful(`${i.roomName}`,roomColor?roomColor:'blue',true) + ' \n'
            }
            return result
        },
        // 下买订单
        buy(roomName:string,rType:ResourceConstant,price:number,amount:number):string{
            var result = Game.market.createOrder({
                type: 'buy' ,
                resourceType: rType,
                price: price,
                totalAmount: amount,
                roomName: roomName   
            });
            if (result == OK) return `[market] ` + colorful(`买资源${rType}的订单下达成功！ 数量为${amount},价格为${price}`,'blue',true)
            else return `[market] ` + colorful(`买资源${rType}的订单出现错误，不能下达！`,'red',true)
        },
        // 下卖订单
        sell(roomName:string,rType:ResourceConstant,price:number,units:number,continues:boolean):string{
            var thisRoom = Game.rooms[roomName]
            if (!thisRoom) return `[market] 不存在房间${roomName}`
            if (!thisRoom.memory.market['order'])thisRoom.memory.market['order'] = []
            var orderDatas = thisRoom.memory.market['order']
            for (var o of orderDatas)
            {
                if(o.rType == rType)
                {
                    o.price = price
                    o.unit = units
                    o.continue = continues
                    o.num = units*3
                    return`[market] 已经检测到房间${roomName}存在卖${rType}的订单 已经调整其价格为${price}，单位为${units}, continue为${continues}!`
                }
            }
            var data:LittleMarketData = {
                        price:price,
                        continue:continues,
                        num:units*3,
                        unit:units,
                        rType:rType,
                    }
            orderDatas.push(data)
            return `[market] 房间${roomName}已经添加卖${rType}的订单 价格为${price}，单位为${units}, continue为${continues}!`
        },
        Csell(roomName:string,rType:ResourceConstant):string{
            var thisRoom = Game.rooms[roomName]
            if (!thisRoom) return `[market] 不存在房间${roomName}`
            for (var i of thisRoom.memory.market['order'])
            {
                if (i.rType == rType)
                {
                    var index = thisRoom.memory.market['order'].indexOf(i)
                    thisRoom.memory.market['order'].splice(index,1)
                    return `[market] 房间${roomName} ${rType}的卖任务已经取消！`
                }
            }
            return `[marekt] 房间${roomName}未侦测到${rType}的卖订单！`
        },
        // 改变价格
        price(id:string,price:number):string{
            var thisOrder = Game.market.getOrderById(id)
            if (!thisOrder) return `[market] 不存在id为${id}的订单！`
            if(Game.market.changeOrderPrice(id,price) == OK)
            return `[market] id为${id}的订单价格已经改成${price} 卖的资源为${thisOrder.resourceType}, 房间在${thisOrder.roomName}！`
            return `[market] id为${id}的订单价格更改失败！！ 卖的资源为${thisOrder.resourceType}, 房间在${thisOrder.roomName}！`
    
        },
        marketPrice(roomName:string,rType:ResourceConstant,price:number):string{
            var thisRoom = Game.rooms[roomName]
            if (!thisRoom) return `[market] 不存在房间${roomName}`
            for (var i of thisRoom.memory.market['order'])
            {
                if (i.rType == rType)
                {
                    i.price = price
                    return `[marekt] 房间${roomName} ${rType}的卖订单价格改为${price}！`
                }
            }
            return `[marekt] 房间${roomName}未侦测到${rType}的卖订单！`
        },
        // 展示该房间卖的资源信息
        sellData(roomName:string):string{
            var thisRoom = Game.rooms[roomName]
            if (!thisRoom) return `[market] 不存在房间${roomName}`
            if (!thisRoom.memory.market['order']) thisRoom.memory.market['order'] = []
            var str = `[market] 房间${roomName}贩卖资源信息如下：\n`
            for (var i of thisRoom.memory.market['order'])
            {
                str += `    资源:${i.rType} 价格:${i.price} 数量:${i.unit} continue:${i.continue}`
            }
            return str
        },
        // 取消订单
        cancel(id:string):string{
            var result = Game.market.cancelOrder(id)
            if (result == OK) return `[market] 取消订单${id}成功!`
            return `[market] 不存在该订单或该订单已经交易完成! id:${id}`
        },
        // 取消某房间所有类型的订单
        cancelRoom(roomName:string,rType:ResourceConstant):string{
            var myOrders = Game.market.getAllOrders(order => order.roomName == roomName && order.resourceType == rType)
            var str = `[market] 房间${roomName} 取消${rType}的订单结果如下：\n`
            for (var i of myOrders)
            {
                str += `${i.id} 结果： ${Game.market.cancelOrder(i.id)}\n`

            }
            return str
        },
        // 获取现在与自己有关的订单
        mine():string{
            var str = ''
            var list = Game.market.getAllOrders(order => isInArray(Object.keys(Memory.ControlPlan),order.roomName))
            if (list.length > 0)
            {
                var str = '[market] 与本账号有关的订单如下：\n'
                for (var i of list)
                {
                    str += `交易房间：${i.roomName} 资源：${i.resourceType} ` + colorful(`交易类型：  ${i.type}`,i.type=='buy'?'blue':'green') + ` 价格： ${i.price} 剩余量： ${i.amount} id: ${i.id}\n`
                }
                return str
            }
            return `[market] 没有订单！`
        },
        // API帮助
        help():string{
            var str = '[market] market API 具体使用语法、规则如下：\n'
            
            str += Colorful('[交易订单] deal(roomName:string,id:string,amount:number):number\n',colorHex(getColor(10)))
            str += Colorful('[查询订单] look(rType:ResourceConstant,marType:"buy"|"sell"):string\n',colorHex(getColor(20)))
            str += Colorful('[下达订单] order(roomName:string,rType:ResourceConstant,price:number,amount:number,marType: ORDER_SELL | ORDER_BUY):string\n',colorHex(getColor(30)))
            str += Colorful('[取消订单] cancel(id:string):string\n',colorHex(getColor(40)))
            str += Colorful('[所有自己订单] mine():string\n',colorHex(getColor(50)))
            // colorHex(getColor(Math.ceil(Math.random()*100+0.1)))
            return str
        }
    },
    help():string{
        /* SuperBitchAPI使用指南！ */
        var str = ''
        str += Colorful('⠄⠄⠄⠄⠄⠄⢠⣿⣋⣿⣿⣉⣿⣿⣯⣧⡰⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄\n',colorHex(getColor(20)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⣿⣿⣹⣿⣿⣏⣿⣿⡗⣿⣿⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄\n',colorHex(getColor(25)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠟⡛⣉⣭⣭⣭⠌⠛⡻⢿⣿⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄\n',colorHex(getColor(30)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⠄⣤⡌⣿⣷⣯⣭⣿⡆⣈⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄\n',colorHex(getColor(35)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⢻⣿⣿⣿⣿⣿⣿⣿⣷⢛⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄\n',colorHex(getColor(40)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣛⣻⣿⠟⣀⡜⣻⢿⣿⣿⣶⣤⡀⠄⠄⠄⠄⠄\n',colorHex(getColor(45)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⠄⢠⣤⣀⣨⣥⣾⢟⣧⣿⠸⣿⣿⣿⣿⣿⣤⡀⠄⠄⠄\n',colorHex(getColor(50)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⠄⢟⣫⣯⡻⣋⣵⣟⡼⣛⠴⣫⣭⣽⣿⣷⣭⡻⣦⡀⠄\n',colorHex(getColor(55)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⢰⣿⣿⣿⢏⣽⣿⢋⣾⡟⢺⣿⣿⣿⣿⣿⣿⣷⢹⣷⠄\n',colorHex(getColor(60)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⢣⣿⣿⣿⢸⣿⡇⣾⣿⠏⠉⣿⣿⣿⡇⣿⣿⡆\n',colorHex(getColor(65)))
        str += Colorful('⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⢸⣿⣿⣿⠸⣿⡇⣿⣿⡆⣼⣿⣿⣿⡇⣿⣿⡇\n',colorHex(getColor(70)))
        str += Colorful('⠇⢀⠄⠄⠄⠄⠄⠘⣿⣿⡘⣿⣿⣷⢀⣿⣷⣿⣿⡿⠿⢿⣿⣿⡇⣩⣿⡇\n',colorHex(getColor(75)))
        str += Colorful('⣿⣿⠃⠄⠄⠄⠄⠄⠄⢻⣷⠙⠛⠋⣿⣿⣿⣿⣿⣷⣶⣿⣿⣿⡇⣿⣿⡇\n',colorHex(getColor(80)))
        str += Colorful('⣿⣿⣿⣿⣿⣿⣿需要 ♂ 什么 ♂ 帮助？⣿⣿⣿⣿⣿⣿⣿\n',colorHex(getColor(15)))
        
        return str
    }
}